package com.upcode.weighing.utils;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

public class SCPUtil {

    private static final Logger logger = LoggerFactory.getLogger(SCPUtil.class);

    //服务器ID
    private static String IP;
    //服务器端口
    private static int PORT;
    //服务器同户名
    private static String USER;
    //服务器密码
    private static String PASSWORD;
    private static Connection connection;
    // 本机的私钥文件
    private static String PRIVATEKEY = "C:/Users/ubuntu/.ssh/id_rsa";
    // 使用用户名和密码来进行登录验证。如果为true则通过用户名和密码登录，false则使用rsa免密码登录
    private static boolean usePassword = true;

    public SCPUtil(String ftpIp, int ftpPort, String ftpUser, String ftpPassword){
        IP = ftpIp;
        PORT = ftpPort;
        USER = ftpUser;
        PASSWORD = ftpPassword;
        connection = new Connection(ftpIp, ftpPort);
    }

    /**
     * ssh用户登录验证，使用用户名和密码来认证
     *
     * @param user
     * @param password
     * @return
     */
    public static boolean isAuthedWithPassword(String user, String password) {
        try {
            return connection.authenticateWithPassword(user, password);
        } catch (IOException e) {
            logger.error(String.format("SSH用户登录验证异常，异常信息为[%s]",e.getMessage()),e);
        }
        return false;
    }

    /**
     * ssh用户登录验证，使用用户名、私钥、密码来认证 其中密码如果没有可以为null，生成私钥的时候如果没有输入密码，则密码参数为null
     *
     * @param user
     * @param privateKey
     * @param password
     * @return
     */
    public static boolean isAuthedWithPublicKey(String user, File privateKey, String password) {
        try {
            return connection.authenticateWithPublicKey(user, privateKey, password);
        } catch (IOException e) {
            logger.error(String.format("SSH用户登录验证异常，异常信息为[%s]",e.getMessage()),e);
        }
        return false;
    }

    /**
     * 判断用密钥认证还是用用户名密码认证
     * @return
     */
    public static boolean isAuth() {
        if (usePassword) {
            return isAuthedWithPassword(USER, PASSWORD);
        } else {
            return isAuthedWithPublicKey(USER, new File(PRIVATEKEY), PASSWORD);
        }
    }

    /**
     * 获取服务器下的文件
     * @param remoteFile
     * @param path
     */
    public String getFile(String remoteFile, String path) {
        String result ="";
        try {
            logger.debug(String.format("等待连接远程服务器,ip:[%s],port:[%s]:userName:[%s],password:[%s]",
                    IP,PORT,USER, PASSWORD));
            connection.connect();
            boolean isAuthed = isAuth();
            if (isAuthed) {
                logger.debug(String.format("[下载文件]远程服务器连接成功,ipAddress:[%s],port:[%s]:userName:[%s],password:[%s]",
                        IP,PORT,USER, PASSWORD));
                SCPClient scpClient = connection.createSCPClient();
                logger.debug(String.format("开始下载远程服务器文件至本地，远程服务器文件路径为[%s],本地目录为[%s]",
                        remoteFile,path));
                scpClient.get(remoteFile, path);
                logger.debug(String.format("远程服务器文件下载成功"));
                result = "下载成功";
            } else {
                logger.debug(String.format("[下载文件]远程服务器连接失败,ipAddress:[%s],port:[%s]:userName:[%s],password:[%s]",
                        IP,PORT,USER, PASSWORD));
                result = "下载失败";
            }
        } catch (IOException e) {
            logger.error(String.format("获取服务器文件异常，异常信息为[%s]",e.getMessage()),e);
            result = "下载失败";
        } finally {
            connection.close();
        }
        return result;
    }

    /**
     * 上传文件至服务器
     * @param localFile
     * @param remoteTargetDirectory
     */
    public String putFile(String localFile, String remoteTargetDirectory) {
        String result ="";
        try {
            logger.debug(String.format("等待连接远程服务器,ip:[%s],port:[%s]:userName:[%s],password:[%s]",
                    IP,PORT,USER, PASSWORD));
            connection.connect();
            boolean isAuthed = isAuth();
            if (isAuthed) {
                logger.debug(String.format("远程服务器连接成功,ip:[%s],port:[%s]:userName:[%s],password:[%s]",
                        IP,PORT,USER, PASSWORD));
                SCPClient scpClient = connection.createSCPClient();
                //上传文件到远程服务器
                logger.debug(String.format("开始上传文件至远程服务器，源文件路径为[%s],目标目录为[%s]",localFile,remoteTargetDirectory));
                scpClient.put(localFile, remoteTargetDirectory);
                logger.debug(String.format("上传文件至远程服务器成功"));
                result = "上传成功";
            } else {
                logger.debug(String.format("远程服务器连接失败,ip:[%s],port:[%s]:userName:[%s],password:[%s]",
                        IP,PORT,USER, PASSWORD));
                result = "上传失败";
            }
        } catch (Exception e) {
            logger.error(String.format("上传文件至远程服务器异常，异常信息为[%s]",e.getMessage()),e);
            result = "上传失败";
        } finally {
            connection.close();
        }
        return result;
    }
}
